package com.hzcx.app.simplechat.ui.group;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hzcx.app.simplechat.api.BaseDialogObserver;
import com.hzcx.app.simplechat.api.BaseObserver;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.model.GroupModel;
import com.hzcx.app.simplechat.ui.chat.ChatGroupSettingActivity;
import com.hzcx.app.simplechat.ui.chat.db.ChatNoticeListDao;
import com.hzcx.app.simplechat.ui.friend.FriendListByLableActivity;
import com.hzcx.app.simplechat.ui.friend.bean.FriendBean;
import com.hzcx.app.simplechat.ui.friend.bean.FriendCityBean;
import com.hzcx.app.simplechat.ui.group.LiveData.GroupInfoBeanLiveData;
import com.hzcx.app.simplechat.ui.group.adapter.GroupMembersSort;
import com.hzcx.app.simplechat.ui.group.adapter.PickContactAdapter;
import com.hzcx.app.simplechat.ui.group.bean.GroupInfoBean;
import com.hzcx.app.simplechat.ui.group.bean.MembersBean;
import com.hzcx.app.simplechat.ui.group.bean.GroupSettingBean;
import com.hzcx.app.simplechat.ui.group.bean.QueryMembersBean;
import com.hzcx.app.simplechat.ui.home.AddFriendActivity;
import com.hzcx.app.simplechat.ui.mine.MineUserInfoActivity;
import com.hzcx.app.simplechat.ui.publicui.ExpandGridView;
import com.hzcx.app.simplechat.ui.publicui.adapter.GroupSettingGridAdapter;
import com.hzcx.app.simplechat.ui.user.UserInfoActivity;
import com.hzcx.app.simplechat.util.UserInfoUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.leanback.widget.VerticalGridView;

import org.litepal.LitePal;
import org.litepal.crud.callback.FindMultiCallback;

import butterknife.BindView;

public class GroupAddFriendsActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.swipe_target)
    GridView mAvatarsEgv;
    @BindView(R.id.swipeToLoadLayout)
    SwipeToLoadLayout swipeToLoadLayout;

//    public static String GroupInfoBeanKey = "GroupAddFriendsActivityGroupInfoBean";
//    GroupInfoBean groupInfoBean;
    public static String GroupInfoBeanKeyGroupID = "QrCodeActivity_GroupInfoBeanKeyGroupID";
    GroupInfoBean groupInfoBean;
    private String groupID;

    private GroupSettingGridAdapter mGroupSettingGridAdapter;
    private List<MembersBean> membersBeans = new ArrayList<>();
    private int page  = 1;
    private String pageSize = "100";

    @Override
    public int getLayout() {
        return R.layout.activity_group_add_friends;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {
        //        groupInfoBean = (GroupInfoBean)getIntent().getSerializableExtra(GroupAddFriendsActivity.GroupInfoBeanKey);
        groupID = getIntent().getStringExtra(GroupInfoBeanKeyGroupID);
        groupInfoBean = GroupInfoBeanLiveData.getGroupInfoBean(groupID);
        tvTitle.setText("群成员(" + groupInfoBean.getMember_total() + ")");
        swipeToLoadLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                getGroupMembers(false);
            }
        });
        initAdapter();
    }


    @Override
    public void initData() {
        getGroupMembers(false);
    }

    private void initAdapter() {
        mGroupSettingGridAdapter = new GroupSettingGridAdapter(this, membersBeans);
        if (groupInfoBean.getMy()!=null){
            if (groupInfoBean.getMy().getIs_admin().equals("Y") || groupInfoBean.getMy().getIs_owner().equals("Y")) {
                mGroupSettingGridAdapter.showDele = true;
            }
        }
        mAvatarsEgv.setAdapter(mGroupSettingGridAdapter);
        mAvatarsEgv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (i >= membersBeans.size()) {
                    LitePal.findAllAsync(FriendBean.class, true).listen(new FindMultiCallback<FriendBean>() {
                        @RequiresApi(api = Build.VERSION_CODES.N)
                        @Override
                        public void onFinish(List<FriendBean> list) {
                            List<FriendBean> friends = GroupMembersSort.sortFriend(membersBeans);
                            Log.i("ChatGroupSetting", "friendList = " + friends.size());
                            if (i == membersBeans.size()) { // 邀请新成员
                                Intent intent = new Intent(GroupAddFriendsActivity.this, GroupCreateActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putSerializable(FriendListByLableActivity.INTENT_LIST_BUNDLE, friends.toArray());
                                intent.putExtras(bundle);
                                intent.putExtra(GroupCreateActivity.GroupCreateActivityGroupID, groupInfoBean.getGroup_id());
                                startActivity(intent);
                            } else if (i == membersBeans.size() + 1) {  // 删除群成员：群主
                                Intent intent = new Intent(GroupAddFriendsActivity.this, ChatGroupDeleteMemberActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putSerializable(FriendListByLableActivity.INTENT_LIST_BUNDLE, friends.toArray());
                                intent.putExtras(bundle);
                                intent.putExtra(GroupCreateActivity.GroupCreateActivityGroupID, groupInfoBean.getGroup_id());
                                startActivity(intent);
                            }
                        }
                    });

                } else {    // 查看好友详情
                    MembersBean membersBean = membersBeans.get(i);
                    if (membersBean.getMember_id() == UserInfoUtil.getUserId()) {   // 点击的群成员是自己
                        startActivity(new Intent(GroupAddFriendsActivity.this, MineUserInfoActivity.class));
                        return;
                    }

                    LitePal.findAllAsync(FriendBean.class, true).listen(new FindMultiCallback<FriendBean>() {
                        @RequiresApi(api = Build.VERSION_CODES.N)
                        @Override
                        public void onFinish(List<FriendBean> list) {
                            for (FriendBean friend: list) {
                                for (FriendCityBean friendCityBean: friend.getCity()) {
                                    if (friendCityBean.getMember_id() == membersBean.getMember_id()) {  // 好友
                                        startActivity(new Intent(GroupAddFriendsActivity.this, UserInfoActivity.class)
                                                .putExtra(UserInfoActivity.INTENT_USER_ID, membersBean.getMember_id()));
                                        return;
                                    }
                                }
                            }
                            //  陌生人
                            Intent intent = new Intent(GroupAddFriendsActivity.this, AddFriendActivity.class);
                            intent.putExtra(AddFriendActivity.INTENT_USER_ID, membersBean.getMember_id());
                            intent.putExtra(AddFriendActivity.INTENT_TYPE, 2);
                            if (groupInfoBean.getProtectedswitch() == 1) {
                                intent.putExtra(AddFriendActivity.PROTECT_GROUP_MEMBER, true);
                            }
                            startActivity(intent);
                        }
                    });
                }
            }
        });
    }

    private void getGroupMembers(boolean refreshTotal) {
        GroupModel.getGroupMembers(this, groupID, String.valueOf(page), pageSize, new BaseDialogObserver<QueryMembersBean>(this) {
            @Override
            protected void onSuccess(QueryMembersBean data) {
                swipeToLoadLayout.setLoadingMore(false);
                if (data.getData()!=null&&!data.getData().isEmpty()){
                    if (page==1){
                        membersBeans.clear();
                        membersBeans.addAll(data.getData());
                        if (refreshTotal){
                            tvTitle.setText("群成员(" + membersBeans.size() + ")");
                        }
                    }else {
                        membersBeans.addAll(data.getData());
                    }
                    mGroupSettingGridAdapter.notifyDataSetChanged();
                }
                page++;

            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                super.onFailure(e, errorMsg);
                swipeToLoadLayout.setLoadingMore(false);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        try {
            if (page==2&&mGroupSettingGridAdapter.getCount()<100){
                page  = 1;
                getGroupMembers(true);
            }
        }catch (Exception e){
            e.printStackTrace();
        }


    }


}
